package com.electronicmallapiidea.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.electronicmallapiidea.constants.Constants;
import com.electronicmallapiidea.constants.RedisConstants;
import com.electronicmallapiidea.entity.LoginForm;
import com.electronicmallapiidea.entity.User;
import com.electronicmallapiidea.entity.dto.UserDTO;
import com.electronicmallapiidea.exception.ServiceException;
import com.electronicmallapiidea.mapper.UserMapper;
import com.electronicmallapiidea.service.UserService;
import com.electronicmallapiidea.utils.TokenUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    RedisTemplate<String, User> redisTemplate;

    @Override
    public UserDTO login(LoginForm loginForm) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginForm.getUsername());
        queryWrapper.eq("password", loginForm.getPassword());
        User user = getOne(queryWrapper);
        if (user == null)
            throw new ServiceException(Constants.CODE_403, "用户名或密码错误");
        String token = TokenUtils.genToken(user.getId().toString(), user.getPassword());
        //把用户存到redis中
        redisTemplate.opsForValue().set(RedisConstants.USER_TOKEN_KEY + token, user);
        //jwt不设置过期时间，值设置redis过期时间
        redisTemplate.expire(RedisConstants.USER_TOKEN_KEY + token, RedisConstants.USER_TOKEN_TTL, TimeUnit.MINUTES);
        //把查到的user的一些属性值赋给userDTO
        UserDTO userDTO = new UserDTO();
        BeanUtil.copyProperties(userDTO, user);
        //设置token
        userDTO.setToken(token);
        return userDTO;
    }

    @Override
    public User register(LoginForm loginForm) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginForm.getUsername());//先获取一下，看看是否被使用
        User user = getOne(queryWrapper);
        if (user != null) {
            throw new ServiceException(Constants.CODE_403, "用户名已被使用");
        } else {
            user = new User();
            BeanUtil.copyProperties(loginForm,user);
            user.setNickname("新用户");
            user.setRole("user");
            save(user);
            return user;
        }
    }

    @Override
    public User getOne(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return getOne(queryWrapper);
    }


}
